<template>
  <div class="connect-page">
    <n-card title="连接到 Ollama 服务" class="connect-card">
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
      >
        <n-form-item path="url" label="Ollama 服务地址">
          <n-input v-model:value="formValue.url" placeholder="例如：http://localhost:11434" />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" @click="handleConnect" :loading="loading">
            连接
          </n-button>
        </n-form-item>
      </n-form>
    </n-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useOllamaStore } from '../store'
import { OllamaAPI } from '../api/ollama'
import { useMessage, NCard, NButton, NForm, NFormItem, NInput } from 'naive-ui'

const router = useRouter()
const store = useOllamaStore()
const message = useMessage()

const formRef = ref(null)
const loading = ref(false)
const formValue = ref({
  url: ''
})

const rules = {
  url: [
    {
      required: true,
      message: '请输入 Ollama 服务地址',
      trigger: ['blur', 'input']
    },
    {
      type: 'url',
      message: '请输入有效的 URL 地址',
      trigger: ['blur', 'input']
    }
  ]
}

async function handleConnect() {
  try {
    await formRef.value?.validate()
    loading.value = true
    const api = new OllamaAPI(formValue.value.url)
    const version = await api.testConnection()
    
    store.setBaseUrl(formValue.value.url)
    store.setConnected(true)
    store.setVersion(version.version)
    
    message.success('连接成功')
    router.push('/dashboard')
  } catch (error) {
    if (error?.message) {
      message.error(error.message)
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.connect-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.connect-card {
  width: 100%;
  max-width: 400px;
}
</style>